package com.hspedu.qqserver.service;

import com.hspedu.qqcommon.Message;
import com.hspedu.qqcommon.MessageType;
import com.hspedu.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;


/**
 * @Author Stringzhua
 * @Date 2024/4/11 22:39
 * description:
 */
public class SendNewsToAllServices implements Runnable {
    @Override
    public void run() {
        //为了可以多次推送新闻,使用while循环
        while (true) {
            System.out.println("请输入服务器要推送的新闻/消息[输入exit表示退出推送服务]");
            String news = Utility.readString(10000);
            if ("exit".equals(news)) {
                break;
            }
            //构建一个消息,群发消息类型
            Message message = new Message();
            message.setSender("服务器");
            message.setMessageType(MessageType.MESSAGE_TO_ALL_MES);
            message.setContent(news);
            message.setSendTime(new Date().toString());

            System.out.println("服务器推送消息给所有人 说:" + news);

            //遍历当前所有的通讯线程,得到socket,并发送message对象
            HashMap<String, ServerConnectClientThread> hm = ManageClientThreads.getHm();
            Set<String> keySet = hm.keySet();
            Iterator<String> iterator = hm.keySet().iterator();
            while (iterator.hasNext()) {
                String onlineUserId = iterator.next().toString();
                //取出线程
//            ServerConnectClientThread serverConnectClientThread = hm.get(onlineUserId);
//            ObjectOutputStream oos =
//                    new ObjectOutputStream(serverConnectClientThread.getSocket().getOutputStream());
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(hm.get(onlineUserId).getSocket().getOutputStream());
                    oos.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
